<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Support\Facades\Validator;
use App\Http\Controllers\Base\BaseController;

class AjaxDataController extends BaseController

{
    /**
     * 根据分类的id获取产品的信息
     *
     * @param Request $request
     *
     * @return array
     */
    function useCatgetGoods(Request $request)
    {
        $cat_id = $request->input('cat_id');
        $list = DB::table('goods_master as gm')
            ->where('gm.category_id', '=', $cat_id)
            ->select(DB::raw('gm.goods_id,gm.goods_code,gm.goods_name,concat(gp.image_url,"",gp.file_name) as image_url'))
            ->leftJoin('goods_picture as gp','gm.goods_id','=','gp.goods_id')
            ->get();
        foreach ($list as $key=>$value){
            $list[$key]->image_url = asset($value->image_url);
        }
        return $this::showReturnCode(1001, $list, '返回产品数据');
    }

    /**
     * 根据产品id获取产品的信息
     *
     * @param Request $request
     *
     * @return array
     */
    function getGoodsInfo(Request $request)
    {
        $goods_id = $request->input('goods_id');
        $list = DB::table('goods_master as a')
            ->where('a.goods_id', '=', $goods_id)
            ->select(DB::raw('a.goods_id,a.goods_code, a.goods_name, a.price,b.color,b.size,b.model'))
            ->leftJoin('goods_model as b','a.goods_id','=','b.goods_id')
            ->first();
        if ($list != false) {
            $list->total_num = houseGoodsTotalNum($goods_id);
        }
        if($request->has('subscribe')){
            $list->subscribe = subscribe_goods($goods_id);
        }
        return $this::showReturnCode(1001, $list, '返回产品数据');
    }

    /**
     * 根据店铺id获取店铺信息
     *
     * @param Request $request
     *
     * @return array
     */
    function getShopMasterInfo(Request $request)
    {
        $shop_id = $request->input('shop_id');
        $list = DB::table('shop_master')->where('shop_id', '=', $shop_id)->first();
        return $this::showReturnCode(1001, $list, '返回产品数据');
    }

    /**
     * 根据店铺id获取店铺列表
     *
     * @param Request $request
     *
     * @return array
     */
    function getShopMasterList(Request $request)
    {
        $corp_id = $request->input('corp_id');
        $list = DB::table('shop_master')->where('corp_id', '=', $corp_id)->select('shop_id', 'shop_name')->get();
        return $this::showReturnCode(1001, $list, '返回产品数据');
    }

    /**
     * 保存用户来电话的订单
     *
     * @param Request $request
     *
     * @return array
     */

    function saveOrder(Request $request)
    {

        $user_id = Cookie::get('user_id');
        $user_name = Cookie::get('user_name');

        $paramData = $request->all();

        $validator = Validator::make($paramData, [
            'order_id' => 'required|unique:user_order|max:255',
            'shop_name' => 'required',
            'money' => 'required',
            'address' => 'required',
            'goods_list' => 'required',

        ])->validate();


        $orderData['user_id'] = $user_id;
        $orderData['user_name'] = $user_name;
        $orderData['order_id'] = $paramData['order_id'];
        $orderData['money'] = $paramData['money'];
        $orderData['consignation_date'] = empty($paramData['weituo_date']) ? toDate(time()) : $paramData['weituo_date'];
        $orderData['create_time'] = toDate(time());
        $orderData['send_goods_time'] = empty($paramData['goods_date']) ? toDate(time()) : $paramData['goods_date'];
        $orderData['name'] = $paramData['shop_name'];
        $orderData['shop_id'] = $paramData['shop_id'];
        $orderData['corp_id'] = $paramData['company_id'];
        $orderData['add'] = empty($paramData['address']) ? '' : $paramData['address'];
        $orderData['add_alias'] = empty($paramData['alias']) ? '' : $paramData['alias'];
        $orderData['tel'] = empty($paramData['mobile']) ? '' : $paramData['mobile'];
        $orderData['postal_code'] = empty($paramData['postal']) ? '' : $paramData['postal'];
        $orderData['fax'] = empty($paramData['fax']) ? '' : $paramData['fax'];
        DB::beginTransaction();
        $ret = DB::table('user_order')->insert($orderData);

        if ($ret != false) {
            $listData = $paramData['goods_list'];
            $detailData = [];
            foreach ($listData as $value) {
                if($value['goods_num'] > 0) {
                    $gData['order_id'] = $orderData['order_id'];
                    $gData['goods_id'] = $value['goods_id'];
                    $gData['goods_num'] = $value['goods_num'];
                    $gData['goods_name'] = $value['goods_name'];
                    $gData['goods_price'] = $value['price'];
                    $gData['size'] = $value['model_info']['size_name'];
                    $gData['color'] = $value['model_info']['color_name'];
                    $gData['model_id'] = $value['model_info']['goods_model_id'];
                    $gData['deliver_time'] = $paramData['goods_date'];
                    $gData['create_time'] = toDate(time());
                    $detailData[] = $gData;
                }
            }
            if (empty($detailData)) {
                DB::rollBack();
                return $this::showReturnCode(1033, [], trans('symessages.ajax_data.detail_data'));
            }
            $ret2 = DB::table('user_order_detailed')->insert($detailData);
            if ($ret2 === true) {
                DB::commit();
                return $this::showReturnCode(1001, [], trans('symessages.ajax_data.insert_success'));
            }
        } else {
            return $this::showReturnCode(1031);
        }

    }

    /**
     * 保存编辑后的订单
     * @param Request $request
     *
     * @return array
     */
    function saveEditOrder(Request $request)
    {

        $user_id = Cookie::get('user_id');
        $user_name = Cookie::get('user_name');

        $paramData = $request->all();

        $validator = Validator::make($paramData, [
            'order_id' => 'required|max:255',
            'address' => 'required',

        ])->validate();

        $orderData['clearing_from'] = $paramData['clearing_from'];
        $orderData['add'] = empty($paramData['address']) ? '' : $paramData['address'];
        $orderData['add_alias'] = empty($paramData['alias']) ? '' : $paramData['alias'];
        $orderData['tel'] = empty($paramData['mobile']) ? '' : $paramData['mobile'];
        $orderData['postal_code'] = empty($paramData['postal']) ? '' : $paramData['postal'];
        $orderData['fax'] = empty($paramData['fax']) ? '' : $paramData['fax'];
        $ret = DB::table('user_order')->where('order_id','=',$paramData['order_id'])->update($orderData);
        return $this::showReturnCode(1001, [], trans('symessages.ajax_data.insert_success'));

    }

    /**
     * 保存供应商采购订单
     * @param Request $request
     *
     * @return array
     */
    function saveSubscribeOrder(Request $request)
    {

        $user_id = Cookie::get('user_id');
        $user_name = Cookie::get('user_name');

        $paramData = $request->all();

        $validator = Validator::make($paramData, [
            'order_id' => 'required|unique:user_order|max:255',
            'goods_list' => 'required',

        ])->validate();


            $listData = $paramData['goods_list'];
            $detailData = [];
            foreach ($listData as $value) {
                if($value['goods_num'] > 0) {
                    $gData['user_id'] = $user_id;
                    $gData['user_name'] = $user_name;
                    $gData['order_id'] = $paramData['order_id'];
                    $gData['goods_id'] = $value['goods_id'];
                    $gData['goods_name'] = $value['goods_name'];
                    $gData['num'] = $value['goods_num'];
                    $gData['state'] = 0;
                    $gData['unit_price'] = $value['price'];
                    $gData['model_id'] = $value['model_info']['goods_model_id'];
                    $gData['color'] = $value['model_info']['color_name'];
                    $gData['size'] = $value['model_info']['size_name'];
                    $gData['total_price'] = $value['price']*$gData['num'];
                    $gData['create_time'] = toDate(time());
                    $gData['scheduled_arrival'] = $value['subscribe_date'];
                    $detailData[] = $gData;
                }
            }
            if (empty($detailData)) {
                return $this::showReturnCode(1033, [], trans('symessages.ajax_data.detail_data'));
            }
            $ret2 = DB::table('suppiler_order')->insert($detailData);
            if ($ret2 === true) {
                return $this::showReturnCode(1001, [], trans('symessages.ajax_data.insert_success'));
            }

    }

    /**
     * 获取供应商订单数据
     * @param Request $request
     *
     * @return array
     */
    public function getSuppilerOrderList(Request $request){
        $order_id = $request->input('order_id');
        if(empty($order_id)){
             return $this::showReturnCode(1003);
        }
        $sql = "select a.*,c.category_name,b.goods_code from suppiler_order a,goods_master b,category_master c where a.goods_id=b.goods_id and b.category_id=c.category_id and a.order_id='$order_id'";

        $list = DB::select($sql);
        foreach ($list as $key=>$value){
            $list[$key]->total_num = houseGoodsTotalNum($value->goods_id);
            $list[$key]->subscribe = subscribe_goods($value->goods_id);
        }

        return $this::showReturnCode(1001, $list, 'get_success');
    }

    /**
     * 入库管理
     * @param Request $request
     *
     * @return array
     */
    public function suppilerGoodsInHouse(Request $request){
        $param = $request->all();
        $ret = in_out_log($param['goodsList'],0,1,1);
        if($ret == true){
            foreach ($param['goodsList'] as $value){
                $map['goods_id'] =$value['goods_id'];
                $map['order_id'] =$value['order_id'];
                $data['update_time'] = toDate(time());
                $data['state'] = 1;
                $data['arrival_num'] = $value['num'];
                DB::table('suppiler_order')->where($map)->update($data);
            }
            return $this::showReturnCode(1001, [], 'success');
        }else{
            return $this::showReturnCode(1033, [], 'fail');
        }
    }

    /**
     * 获取用户订单的详情列表
     * @param Request $request
     *
     * @return array
     */
    public function getUserOrderDetailedList(Request $request){
        $order_id = $request->input('order_id');
        $list = DB::table('user_order_detailed')->where('order_id','=',$order_id)->get();
        foreach ($list as $key=>$value){
            $list[$key]->total_num = houseGoodsTotalNum($value->goods_id);
        }
        return $this::showReturnCode(1001, $list, 'success');
    }

    /**
     * 根据订单商品出库管理
     * @param Request $request
     *
     * @return array
     */
    public function userOutGoodsFromHouse(Request $request){
        $user_id = Cookie::get('user_id');
        $user_name = Cookie::get('user_name');

        $paramData = $request->all();

        $validator = Validator::make($paramData, [
            'order_id' => 'required|max:255',
            'goods_list' => 'required',

        ])->validate();

        DB::beginTransaction();

        $listData = $paramData['goods_list'];
        $detailData = [];
        $total_send_money = 0;
        foreach ($listData as $value) {
            $map['order_id'] = $paramData['order_id'];
            $map['goods_id'] = $value['goods_id'];
            $map['model_id'] = $value['model_info']['goods_model_id'];
            $gData = [];
            if($value['goods_num'] > 0) {
                //TODO 可以传递个仓库id，相当于从哪个仓库发货，默认在总仓库
                $gData['warehouse_id'] = 1;
                $gData['deliver_state'] = 1;
                $gData['deliver_time'] = today();
                $gData['courier_number'] = $paramData['express_waybill_code'];

                $gUpdate = $gData;

                $gData['order_id'] = $paramData['order_id'];
                $gData['goods_id'] = $value['goods_id'];
                $gData['num'] = $value['goods_num'];
                $gData['model_info'] = ['goods_model_id'=>$value['model_info']['goods_model_id'],'size_name'=>$value['model_info']['size_name'],'color_name'=>$value['model_info']['color_name']];
                $detailData[] = $gData;

                $total_send_money = $total_send_money + ($value['goods_num'] * $value['price']);
            }else{
                $gData['warehouse_id'] = 1;
                $gData['deliver_state'] = 1;
                $gData['deliver_time'] = today();
                $gData['courier_number'] = $paramData['express_waybill_code'];
                $gUpdate = $gData;
            }
            DB::table('user_order_detailed')->where($map)->update($gUpdate);
        }
        $orderData['deliver_state'] = 1;
        $orderData['send_goods_total_money'] = $total_send_money;
        DB::table('user_order')->where('order_id','=',$paramData['order_id'])->update($orderData);
        if (empty($detailData)) {
            DB::rollBack();
            return $this::showReturnCode(1033, [], trans('symessages.ajax_data.detail_data'));
        }else{
            DB::commit();
            in_out_log($detailData,1,0,1);
        }

        return $this::showReturnCode(1001, [], trans('symessages.ajax_data.out_goods_form_house'));
    }

    /**
     * 修改入金金额和支付状态
     * @param Request $request
     *
     * @return array
     */
    public function setOrderInMoney(Request $request){
        $money = $request->input('money');
        $order_id = $request->input('order_id');
        DB::table('user_order')->where('order_id','=',$order_id)->update(['state'=>0,'actual_money'=>$money,'in_money_date'=>toDate(time())]);
        return $this::showReturnCode(1001, [], trans('symessages.ajax_data.money_in_order_success'));
    }

    /** 盘点处理
     * @param Request $request
     *
     * @return array
     */
    function takeStock(Request $request)
    {

        $user_id = Cookie::get('user_id');
        $user_name = Cookie::get('user_name');

        $paramData = $request->all();

        $validator = Validator::make($paramData, [
            'order_id' => 'required|unique:take_tock_master|max:255',
            'goods_list' => 'required',

        ])->validate();

        $orderData['type'] = $paramData['type'];
        $orderData['user_id'] = $user_id;
        $orderData['user_name'] = $user_name;
        $orderData['order_id'] = $paramData['order_id'];
        $orderData['create_time'] =toDate(time());
        $orderData['update_time'] =toDate(time());
        DB::beginTransaction();
        $ret = DB::table('take_tock_master')->insert($orderData);

        if ($ret != false) {
            $listData = $paramData['goods_list'];
            $detailData = [];
            foreach ($listData as $value) {
                if(!empty($value['goods_num']) && $value['goods_num'] !==0) {
                    $gData['order_id'] = $orderData['order_id'];
                    $gData['goods_id'] = $value['goods_id'];
                    $gData['num'] = $value['goods_num'];
                    $gData['model_info'] = ['goods_model_id'=>$value['model_info']['goods_model_id'],'color_name'=>$value['model_info']['color_name'],'size_name'=>$value['model_info']['size_name']];
                    $gData['goods_name'] = $value['goods_name'];
                    if($orderData['type'] == 2){
                        $gData['remark'] = empty($value['remark']) ? '' : $value['remark'];
                        $gData['goods_type'] = $value['goods_type'];
                    }
                    $detailData[] = $gData;
                }
            }
            if (empty($detailData)) {
                DB::rollBack();
                return $this::showReturnCode(1033, [], trans('symessages.ajax_data.detail_data'));
            }
            if($orderData['type'] == 2){
                $ret = in_out_log($detailData,3,2,1);
            }else{
                $ret = in_out_log($detailData,2,2,1);
            }
            DB::commit();
            return $this::showReturnCode(1001, [], trans('symessages.ajax_data.insert_success'));
        } else {
            return $this::showReturnCode(1031);
        }

    }

    /** 库存调整处理
     * @param Request $request
     *
     * @return array
     */
    function takeStockChange(Request $request)
    {

        $user_id = Cookie::get('user_id');
        $user_name = Cookie::get('user_name');

        $paramData = $request->all();

        $validator = Validator::make($paramData, [
            'order_id' => 'required|unique:take_tock_master|max:255',
            'goods_list' => 'required',

        ])->validate();


        $orderData['user_id'] = $user_id;
        $orderData['user_name'] = $user_name;
        $orderData['order_id'] = $paramData['order_id'];
        $orderData['create_time'] =toDate(time());
        $orderData['update_time'] =toDate(time());
        DB::beginTransaction();
        $ret = DB::table('take_tock_master')->insert($orderData);

        if ($ret != false) {
            $listData = $paramData['goods_list'];
            $detailData = [];
            foreach ($listData as $value) {
                if($value['goods_num'] > 0) {
                    $gData['order_id'] = $orderData['order_id'];
                    $gData['goods_id'] = $value['goods_id'];
                    $gData['num'] = $value['goods_num'];
                    $gData['goods_name'] = $value['goods_name'];
                    $gData['goods_price'] = $value['price'];
                    $detailData[] = $gData;
                }
            }
            if (empty($detailData)) {
                DB::rollBack();
                return $this::showReturnCode(1033, [], trans('symessages.ajax_data.detail_data'));
            }
            $ret = in_out_log($detailData,2,2,1);
            DB::commit();
            return $this::showReturnCode(1001, [], trans('symessages.ajax_data.insert_success'));
        } else {
            return $this::showReturnCode(1031);
        }

    }

    /**
     * 获取尺寸里面的数据
     * @param Request $request
     *
     * @return array
     */
    public function getSizeArr(Request $request){
        $id = $request->input('id');
        $list = get_size_list($id);
        return $this::showReturnCode(1001, $list, trans('symessages.ajax_data.insert_success'));
    }

    /**
     * 获取商品的模型信息
     * @param Request $request
     *
     * @return array
     */
    public function getModelInfo(Request $request){
        $goods_id = $request->input('goods_id');
        $list = DB::table('goods_model')->where(['goods_id'=>$goods_id])->get();
        if($list !=false){
            foreach ($list as $key=>$value){
                $list[$key]->color_name = fun_colors($value->color);
                $list[$key]->size_name = fun_size($value->size);
            }
        }
        return $this::showReturnCode(1001, $list, trans('symessages.ajax_data.get_data_success'));
    }

    /**
     * 根据尺寸获取商品的库存
     * @param Request $request
     *
     * @return array
     */
    public function userSizeGetGoodsNum(Request $request){
        $goods_id = $request->input('goods_id');
        $model_id = $request->input('model_id');
        $list = DB::table('storehouse_detailed_size')->where(['goods_id'=>$goods_id,'model_id'=>$model_id])->first();
        return $this::showReturnCode(1001, $list, trans('symessages.ajax_data.insert_success'));
    }

    /**
     * 获取分类信息
     * @param Request $request
     *
     * @return array
     */
    public function getCategoryInfo(Request $request){
        $category_id = $request->input('category_id');
        $info = DB::table('category_master')->where('category_id','=',$category_id)->first();
        return $this::showReturnCode(1001, $info, trans('symessages.ajax_data.get_data_success'));
    }

    /**
     * 添加商品分类
     * @param Request $request
     *
     * @return array
     */
    public function saveCategory(Request $request){
        $param = $request->all();
        $validator = Validator::make($param, [
            'category_code' => 'required',
            'category_name' => 'required',
            'sort' => 'integer'
        ])->validate();


        if(isset($param['category_id'])){
            $category_id = $param['category_id'];
            unset($param['category_id']);
            unset($param['_token']);
            $param['updated_at'] = toDate(time());
            DB::table('category_master')->where(['category_id'=>$category_id])->update($param);
        }else{
            unset($param['category_id']);
            unset($param['_token']);
            $param['created_at'] = toDate(time());
            $info = DB::table('category_master')->where('category_id','=',$param['pid'])->select('category_id','path')->first();
            $param['path']= $param['pid']!=0 ? $info->path.'-'.$info->category_id : 0;
            DB::table('category_master')->insert($param);
        }
        return $this::showReturnCode(1001, [], trans('symessages.ajax_data.insert_success'));

    }

    /**
     * 删除商品分类
     * @param Request $request
     *
     * @return array
     */
    public function delCategory(Request $request){
        $id = $request->input('category_id');
        $ret = DB::table('category_master')->where('category_id','=',$id)->update(['delete_flg'=>1]);
        return $this::showReturnCode(1001, [], trans('symessages.ajax_data.del_success'));
    }

    public function uploadCsv(Request $request){
        $param = $request->all();
        if ($request->hasFile('file')) {
            $ext=$request->file('file')->getClientOriginalExtension();
            // 新的文件名
            $newFile=time().rand().".".$ext;
            // 上传文件操作

           $content = $request->file('file')->get();
           dump($content);
            $request->file('file')->move('./uploads/temp/',$newFile);

        }
        dump($param);
    }

}
